package com.postracker.postracker.io.csv;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.postracker.postracker.io.FileBasedTable;
import com.postracker.postracker.io.Table;

public class TablesFolder implements Table {
	private File tablesFolder;
	private FileBasedTable tableContentProvider;
	private List<String[]> allTableRows = new ArrayList<String[]>();
	private File[] filesInFolder;

	public TablesFolder(File tablesFolder, FileBasedTable tableContentProvider) {
		this.tablesFolder = tablesFolder;
		this.tableContentProvider = tableContentProvider;
	}

	@Override
	public List<String[]> getRows() {
		allTableRows.clear();
		loadAllFiles();
		return allTableRows;
	}

	private void loadAllFiles() {
		filesInFolder = tablesFolder.listFiles();
		if (emptyFolder()) {
			return;
		}
		for (File file : filesInFolder) {
			loadFile(file);
		}
	}

	private boolean emptyFolder() {
		return filesInFolder == null;
	}

	private void loadFile(File file) {
		tableContentProvider.setFile(file);
		allTableRows.addAll(tableContentProvider.getRows());
	}

	@Override
	public String getTableName() {
		throw new UnsupportedOperationException(
				"TableFolder is not linked to one table or file.");
	}

}
